package com.imy.common.util;

import android.graphics.Bitmap;
import android.graphics.Matrix;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

public class BitmapUtils {


    public static boolean savePath(String path,int quality,Bitmap bitmap){
        File file = new File(path);
        if (file.exists()){
            file.delete();
        }
        //获取后缀名
        Bitmap.CompressFormat format;
        if (path.endsWith(".jpg")){
            format =Bitmap.CompressFormat.JPEG;
        }else if (path.endsWith(".png")){
            format=Bitmap.CompressFormat.PNG;
        }else {
            format=Bitmap.CompressFormat.PNG;
        }
        try {
            FileOutputStream saveImgOut = new FileOutputStream(file);
            bitmap.compress(format,quality,saveImgOut);
            saveImgOut.flush();
            saveImgOut.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    public static boolean savePath(String path, Bitmap bitmap){
      return   savePath(path,100,bitmap);
    }

    public static Bitmap scaleBitmap(Bitmap origin, int newWidth, int newHeight) {
        if (origin == null) {
            return null;
        }
        int height = origin.getHeight();
        int width = origin.getWidth();
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        return Bitmap.createBitmap(origin, 0, 0, width, height, matrix, false);
    }

    public static Bitmap scaleBitmap(Bitmap origin,float scale){
        if (origin == null) {
            return null;
        }
        int height = origin.getHeight();
        int width = origin.getWidth();
        Matrix matrix = new Matrix();
        matrix.postScale(scale, scale);
        return Bitmap.createBitmap(origin, 0, 0, width, height, matrix, false);
    }
}
